package forum.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;

import forum.shared.Delimiters;
import forum.shared.ServerResponse;

public class OnlineUsersDialog extends Screen {
	DialogBox dialog;
	VerticalPanel vPanel;
	FlexTable usersTbl;
	Button closeBtn;
	Label errorLbl;
	
	public OnlineUsersDialog() {
		init();
		retrieveOnlineUsers();
	}

	private void retrieveOnlineUsers() {
		ForumServiceAsync forumSvc = GWT.create(ForumService.class);
		
		// Set up the callback object.
	    AsyncCallback<ServerResponse> callback = new AsyncCallback<ServerResponse>() {
	    	public void onFailure(Throwable caught) {
	    		errorLbl.setText("Communication error. Please retry later.");
	    		errorLbl.setVisible(true);
	    	}
	    	//On successful communication.
			@Override
			public void onSuccess(ServerResponse response) {
				if (response!=null && response.hasExecuted()) {
					String[] users = response.getResponse()
					.split(Delimiters.MSG_PARTS);
					
//					usersTbl.setTitle("There are " + users[0] + " online users:");
					for (int i=0; i<users.length; i++) {
						usersTbl.setText(i, 0, users[i]);
					}
	            } 
				else {
					errorLbl.setText(response!=null ? 
							response.getResponse() : "Unknown Error...");
					errorLbl.setVisible(true);
	            }
			}
	    };
	    
	 forumSvc.sendMsg("OnlineUsers", callback);
	}


	@Override
	protected void createComponents() {
		dialog = new DialogBox();
		vPanel = new VerticalPanel();
		usersTbl = new FlexTable();
		closeBtn = new Button("Close");
		errorLbl = new Label();
	}

	@Override
	protected String getInput() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void setActions() {
		closeBtn.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				dialog.hide();
			}
		});
	}

	@Override
	protected void setStyle() {
		dialog.setText("Online users");
		dialog.addStyleName("dialogBoxHeader");
		vPanel.addStyleName("dialogBox");
		closeBtn.addStyleName("button");
		errorLbl.addStyleName("errorLabel");
	}

	@Override
	protected void setTabOrder() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setupDisplayInMainPanel() {
		dialog.center();
	}

	@Override
	protected void setupScreenDisplay() {
		vPanel.add(usersTbl);
		vPanel.add(closeBtn);
		dialog.setWidget(vPanel);
		errorLbl.setVisible(false);
	}

}
